package kino.command;

import kino.client.KinoClient;
import kino.common.KinoConstant;
import kino.database.KinoDB;
import kino.object.KinoObject;
import kino.object.KinoObjectTypeEnum;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@KinoCommandEnable
public class HdelCommand extends AbstractKinoCommand{
    @Override
    public String doExecute(KinoClient client, String... argv) {
        KinoDB kinoDB = client.getDb();
        Map<String, KinoObject> dict = kinoDB.getDict();
        KinoObject kinoObject = dict.get(argv[0]);
        if (kinoObject != null && !KinoObjectTypeEnum.KINO_HASH.equals(kinoObject.getType())) {
            return KinoConstant.wrongtypeerr;
        }
        int count = 0;
        if (kinoObject != null) {
            HashMap<String, String> map = (HashMap) kinoObject.getObj();
            count += map.remove(argv[1]) != null ? 1 : 0;
            Map<String, Object> extParam = client.getExtParam();
            // 处理其他需要删除的filed
            if (extParam != null && extParam.containsKey("extKeys")) {
                for (String filed : (List<String>)extParam.get("extKeys")) {
                    count +=  map.remove(filed) != null ? 1 : 0;
                }
            }
        }
        return commandEncoder.encode(count);
    }

    @Override
    public Integer getArgc() {
        return 2;
    }

    @Override
    public String getCommandName() {
        return "hdel";
    }

    @Override
    public boolean aofFlag() {
        return true;
    }

    @Override
    public boolean hasExtParam() {
        return true;
    }
    protected ExtParamParseResult doExtParamParse(String... argv) {
        ExtParamParseResult paramParseResult = new ExtParamParseResult();
        paramParseResult.setSuccess(true);
        Map<String, Object> extParam = new HashMap<>();
        List<String> extList = new ArrayList<>();
        extParam.put("extKeys", extList);
        paramParseResult.setExtParam(extParam);
        for (int i = 1; i < argv.length;i++) {
            extList.add(argv[i]);
        }
        return paramParseResult;
    }
}
